package customlists;

import java.util.ArrayList;

import model.Group;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import database.GroupContactsAdapter;

public class GroupListAdapter extends BaseAdapter {
	
	private ArrayList<Group> groupResults;
	private LayoutInflater mInflater;
	Context context;
	
	public GroupListAdapter(Context context,ArrayList<Group> results){
		groupResults=results;
		mInflater = LayoutInflater.from(context);
		this.context=context;
	}
	
	public int getCount() {
		return groupResults.size();
	}

	public Object getItem(int position) {
		return groupResults.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if(convertView==null){
			holder = new ViewHolder();
			convertView =mInflater.inflate(phone.book.R.layout.simplelistview, null);
			holder.img=(ImageView) convertView.findViewById(phone.book.R.id.imageView1);
			holder.groupName=(TextView) convertView.findViewById(phone.book.R.id.listitems);
			holder.contactsCount=(TextView) convertView.findViewById(phone.book.R.id.groupCount);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		holder.groupName.setText(groupResults.get(position).getGroupName());
		int count=getContactsCount(groupResults.get(position).getId());
		holder.contactsCount.setText("("+count+")");
		holder.id=groupResults.get(position).getId();
		return convertView;
	}
	private int getContactsCount(int groupId) {
		GroupContactsAdapter gc=new GroupContactsAdapter(context);
		gc.open();
		Cursor c=gc.fetchAllContactsInGroup(groupId);	
		int count;
		if(c==null){
			count = 0;
		}else{
			count = c.getCount();			
		}
		gc.close();
		c.close();
		return count;
	}
	static class ViewHolder {
		  int id;   
		  ImageView img;
		  TextView groupName;
		  TextView contactsCount;
	}
}
